﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.IO;

namespace WISD.CarFriend.Web.Admin.Tools
{
    /// <summary>
    /// AJAX单文件上传页
    /// </summary>
    public class SingleUpload : IHttpHandler
    {
        private readonly string m_FileType = "GIF|JPG|PNG|BMP|RAR|ZIP|DOC|XLS|AVI|MPG|WMV|RMVB";    //文件类型
        private readonly int m_FileSize = 5120;   //文件大小0为不限制
        private string m_FilePath = "/UploadFiles/"; //上传目录名

        public void ProcessRequest(HttpContext context)
        {
            // 检验上传文件是否为空
            HttpPostedFile httpPostedFile = context.Request.Files["FileUpload"];
            if (httpPostedFile == null)
            {
                context.Response.Write("{msg: 0, msbox: \"请选择要上传文件！\"}");
                return;
            }

            // 上传文件
            string message = this.UploadFile(httpPostedFile);

            //删除已存在的旧文件
            string fileUrl = context.Request.Params["txtImagePath"];
            if (!string.IsNullOrEmpty(fileUrl))
            {
                string filename = HttpContext.Current.Server.MapPath(fileUrl);
                if (File.Exists(filename))
                {
                    File.Delete(filename);
                }
            }

            //返回成功信息
            context.Response.Write(message);
        }


        public bool IsReusable
        {
            get
            {
                return false;
            }
        }


        private string UploadFile(HttpPostedFile httpPostedFile)
        {
            try
            {
                // 验证文件类型
                string fileExt = httpPostedFile.FileName.Substring(httpPostedFile.FileName.LastIndexOf(".") + 1);
                if (!CheckFileExt(this.m_FileType, fileExt))
                {
                    return "{msg: 0, msbox: \"不允许上传" + fileExt + "类型的文件！\"}";
                }

                // 验证文件大小
                if (this.m_FileSize > 0 && httpPostedFile.ContentLength > this.m_FileSize * 1024)
                {
                    return "{msg: 0, msbox: \"文件超过限制的大小啦！\"}";
                }

                // 生成文件名
                string fileName = DateTime.Now.ToString("yyyyMMddHHmmssff") + "." + fileExt;

                // 生成文件路径
                string filePath = this.m_FilePath;
                if (this.m_FilePath.StartsWith("/") == false)
                {
                    filePath = "/" + this.m_FilePath;
                }
                if (this.m_FilePath.EndsWith("/") == false)
                {
                    filePath = this.m_FilePath + "/";
                }
                filePath += DateTime.Now.ToString("yyyyMMdd") + "/";

                // 检查文件路径是否存在
                string fileFullPath = AppDomain.CurrentDomain.BaseDirectory + filePath;    //物理完整路径
                if (!Directory.Exists(fileFullPath))
                {
                    Directory.CreateDirectory(fileFullPath);
                }

                //保存文件
                httpPostedFile.SaveAs(fileFullPath + fileName);

                return "{msg: 1, msbox: \"" + filePath + fileName + "\"}";
            }
            catch
            {
                return "{msg: 0, msbox: \"上传过程中发生意外错误！\"}";
            }
        }


        /// <summary>
        /// 检查是否为合法的上传文件
        /// </summary>
        /// <returns></returns>
        private bool CheckFileExt(string fileType, string fileExt)
        {
            string[] allowExt = fileType.Split('|');
            for (int i = 0; i < allowExt.Length; i++)
            {
                if (allowExt[i].ToLower() == fileExt.ToLower())
                {
                    return true;
                }
            }
            return false;
        }

    }
}